package com.tfriend.framework;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.AbstractView;

import com.tfriend.framework.xml.Dataset;

/**
 * ResponseOutboundXML.java 
 * 
 */
public class ResponseXML extends AbstractView {

    @Override
    protected void renderMergedOutputModel(Map model,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        response.setContentType("text/xml;charset=EUC-KR");
        response.setCharacterEncoding("EUC-KR");
        ServletOutputStream out = response.getOutputStream();
        out.print(extractAndDrawXML(model));
        out.flush();
    }
    
    String extractAndDrawXML(Map model) throws Exception {
        StringBuffer buf = new StringBuffer();
    	String[] keys = getMapKeys(model);
        List list = null;
        buf.append("<?xml version=\"1.0\" encoding=\"euc-kr\"?>\n");
        buf.append("<root>\n");
        Dataset dataset = null;
        for (int i=0; i < keys.length; i++) {
           list = (List) model.get(keys[i]);
           buf.append(new String(drawDataSet(keys[i], list).getBytes(),"ISO-8859-1"));
        }
        
        buf.append("</root>\n");
    	return buf.toString();
    }
    
    String drawDataSet(String datasetName, List rows) {
        StringBuffer buf = new StringBuffer();
        buf.append("\t<dataset name=\"" + datasetName + "\" type=\"OUTPUT\">\n");
        if (rows != null) {
	        for (int i=0; i < rows.size(); i++) {
	            buf.append("\t<row n=\"" + (i + 1) +"\" type=\"SELECT\">\n");
	            Map cols = (Map)rows.get(i);
	            Iterator it = cols.keySet().iterator();
	            while(it.hasNext()) {
	                String key = (String)it.next();
	                buf.append("\t\t<col name=\"" + key + "\">");
	                buf.append("<![CDATA[");
	                buf.append(cols.get(key));
	                buf.append("]]></col>\n");
	            }
	            buf.append("\t</row>\n");
	        }
        }
        buf.append("\t</dataset>\n");
        return buf.toString();
    }
    
    String[] getMapKeys(Map map) {
        if (map == null) {
            return null;
        }
        String[] ret = new String[map.size()];
        int inc = 0;
        for (Iterator i = map.keySet().iterator(); i.hasNext();) {
            ret[inc++] = (String) i.next();
        }

        return ret;
    }
}

